package com.health.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class JwtUtil {

    //密钥
    private static final String SECRET_KEY = "fsdgfsadgrgehr";

    /**
     * 生成Jwt
     *
     * @param claims 自定义负载（如用户ID、角色等）
     * @return Token字符串
     */
    public static String createJwt(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims) // 自定义数据
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes(StandardCharsets.UTF_8)) // 签名算法
                .compact();
    }

    /**
     * 解析Jwt
     *
     * @param jwt JWT字符串
     * @return 负载数据
     */
    public static Claims parseJwt(String jwt) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) {
        //eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiJ9.0SZwY6yDpzZ-72jN12oheYMMKoLE2F77MPVo1SsPMlY
        //eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiJ9.0SZwY6yDpzZ-72jN12oheYMMKoLE2F77MPVo1SsPMlY
        //eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiJ9.0SZwY6yDpzZ-72jN12oheYMMKoLE2F77MPVo1SsPMlY
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXNpIn0=.0SZwY6yDpzZ-72jN12oheYMMKoLE2F77MPVo1SsPMlY";
        Claims map = parseJwt(jwt);
        System.out.println(map);


        /*Map<String, Object> claims = Map.of("id", 1, "username", "admin");
        String jwt1 = createJwt(claims);
        String jwt2 = createJwt(claims);
        String jwt3 = createJwt(claims);

        System.out.println(jwt1);
        System.out.println(jwt2);
        System.out.println(jwt3);


        Claims map1 = parseJwt(jwt1);
        Claims map2 = parseJwt(jwt2);
        Claims map3 = parseJwt(jwt3);
        System.out.println(map1);
        System.out.println(map2);
        System.out.println(map3);*/
    }
}